package com.wbdca.crawler.common;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.http.ProtocolException;

import java.io.IOException;
import java.net.URI;

public class ConnectionPool {
    private static final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

    public static int limitRemain = 0;

    static {
        connectionManager.setMaxTotal(100);
        connectionManager.setDefaultMaxPerRoute(30);
    }

    public static String getStatus() {
        return connectionManager.getTotalStats().toString();
    }

    public static CloseableHttpClient getClient(){
        System.out.println(connectionManager.getTotalStats());
        return HttpClients.custom().setConnectionManager(connectionManager).build();
    }

    public static CloseableHttpResponse getResponse(URI uri){
        HttpGet httpGet = new HttpGet(uri);
        FineGrainedTokens.addAuthorization(httpGet);
        CloseableHttpResponse response = null;
        try {
            response = getClient().execute(httpGet);
            if(response.getHeader("X-RateLimit-Remaining") != null
                    && (limitRemain = Integer.parseInt(response.getHeader("X-RateLimit-Remaining").getValue())) == 0){
                Message.warn("ConnectionPool.getResponse", "Rate Limit Expired. Trying to update the Fine Grained Token.");
                FineGrainedTokens.updatePointer();
            }
            if(response.getCode() == 404){
                Message.warn("ConnectionPool.getResponse", "Receive 404 Code while accessing " + uri);
                return null;
            }
        } catch (IOException | ProtocolException e) {
            System.out.println(e.getMessage());
        }
        return response;
    }


}
